import json
from typing import Optional, List


def get_silent_chunks(silent_timestamp):
    if not silent_timestamp:  # 如果列表为空，直接返回空列表
        return []

    sublists = [[]]  # 初始化子列表容器，包含一个空子列表
    for i in range(len(silent_timestamp)):
        # 如果子列表为空或者当前数字与子列表最后一个数字连续
        if not sublists[-1] or silent_timestamp[i] == sublists[-1][-1] + 1:
            # 将当前数字添加到子列表末尾
            sublists[-1].append(silent_timestamp[i])
        else:
            # 当前数字与子列表最后一个数字不连续，开始一个新的子列表
            sublists.append([silent_timestamp[i]])

    return sublists


def extract_silent_times(silent_times, interval=2):
    last_silent_time = 0
    end_time = 86400
    ranges = []
    for silent_time in silent_times:
        # silent_time = silent_time.strip("\n")
        # silent_time_int = timestamp2int(silent_time)
        if silent_time - last_silent_time < interval:
            last_silent_time = silent_time
            continue
        else:
            ranges.append((last_silent_time, silent_time))
            # if silent_time_int - last_silent_time > 1800:
            #     print(silent_time_int, last_silent_time)
            last_silent_time = silent_time

    if end_time - last_silent_time > interval:
        ranges.append((last_silent_time, end_time))

    return ranges


def make_valid_ranges(silent_points: List):
    if isinstance(silent_points, str):
        with open(silent_points, "r") as f:
            silent_timestamp = json.loads(f.read())
    else:
        silent_timestamp = silent_points
    silent_chunks = get_silent_chunks(silent_timestamp)
    silent_timestamp = [t[-1] for t in silent_chunks]
    ranges = extract_silent_times(silent_timestamp)
    return ranges


def merge_ranges(ranges, chunk_size):
    duration = 0
    new_ranges = []
    merge_ranges = ranges[0]
    for i in range(1, len(ranges)):
        cur_range_ = ranges[i]
        pre_range_ = ranges[i - 1]
        duration += (cur_range_[1] - pre_range_[0])
        if duration > chunk_size:
            new_ranges.append(merge_ranges)
            duration = 0
            merge_ranges = ranges[i]
        else:
            merge_ranges = (merge_ranges[0], cur_range_[1])
    if len(merge_ranges) > 0:
        new_ranges.append(merge_ranges)
    return new_ranges


def seconds_to_hms(seconds_num: int):
    """
    输入秒数 转换为 时分秒输出
    param: seconds_num integer 666
    return: hms str 00:00:00a
    """
    m, s = divmod(seconds_num, 60)
    h, m = divmod(m, 60)
    hms = "%02d:%02d:%02d" % (h, m, s)
    return hms
